use crate::common::AppState;
use crate::error::AppError;
use chrono::{DateTime, Local};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;

#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, FromRow)]
pub struct Chat {
    pub id: i32,
    pub name: String,
    pub user_id: i32,
    pub members_id: String,
    pub message_id: i32,
    pub chat_type: i8,
    pub content: String,
    pub create_at: DateTime<Local>,
    pub update_at: DateTime<Local>,
}

impl AppState {
    pub async fn create_chat(&self, chat: Chat) -> Result<u64, AppError> {
        let res = sqlx::query(
            r#"
                    INSERT INTO chats (name, user_id, members_id, message_id, chat_type, content, create_at, update_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                "#)
            .bind(chat.name)
            .bind(chat.user_id)
            .bind(chat.members_id)
            .bind(chat.message_id)
            .bind(chat.chat_type)
            .bind(chat.content)
            .bind(chat.create_at)
            .bind(chat.update_at)
            .execute(&self.pool).await?;

        if res.rows_affected() == 1 {
            Ok(res.last_insert_id())
        } else {
            Err(AppError::ChatError("Error creating chat".to_string()))
        }
    }
}
